{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "--------\n",
    "* 记录人：王荟玲\n",
    "* 主要参考文档：\n",
    "> 1.[pyhton官方文档](https://docs.python.org/3/tutorial/controlflow.html#defining-functions)\n",
    "> 2. [blog_函数](https://www.cnblogs.com/xuzhichao/p/11570285.html)\n",
    "--------"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 内容概括\n",
    "\n",
    "> 1. 定义\n",
    "> 2. 使用\n",
    "> 3. 返回值\n",
    "> 4. 使用注释改进文档\n",
    "> 5. 传递任意数量的实参\n",
    "> 6. 函数与模块"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. 定义\n",
    "\n",
    "-----\n",
    "def:定义函数的关键字\n",
    "fib:函数名\n",
    "(n):定义函数的参数\n",
    "代码块：\n",
    "    a,b = 0,1\n",
    "    while a < n:\n",
    "        print(a,end='')\n",
    "        a,b = b,a+b\n",
    "    print()\n",
    "    \n",
    "-----\n",
    "* 定义函数\n",
    "\n",
    "> 1. 写def：def是定义函数的第一步\n",
    "> 2. 写特定函数的名称：def function_name\n",
    ">> 1. function_name 遵循变量名称定义规则\n",
    ">3. 函数名称后加上“():”：def function_name():  ==> f(x) = 2x\n",
    "\n",
    "* 书写函数体：\n",
    "\n",
    "> 1. 函数注释\n",
    "> 2. 写函数的具体操作（函数体）\n",
    "> 3. 注意：函数也是有TAP键缩进\n",
    "\n",
    "* 使用函数（函数的调用）\n",
    "\n",
    "> 1. function_name()\n",
    "\n",
    "* 函数存在的意义"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "def fib(n):     # write Fibonacci series up to n\n",
    "    \"\"\"print a fibonacci series up to n.\"\"\"\n",
    "    a,b = 0,1\n",
    "    while a < n:\n",
    "        print(a, end='')\n",
    "        a,b = b,a+b\n",
    "    print()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "011235813\n"
     ]
    }
   ],
   "source": [
    "fib(15)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on function fib in module __main__:\n",
      "\n",
      "fib(n)\n",
      "    print a fibonacci series up to n.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "help(fib)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 尝试书写一个hello world 的函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "def hey():\n",
    "    \"\"\"print hello world\"\"\"\n",
    "    print(\"hello world!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello world!\n"
     ]
    }
   ],
   "source": [
    "hey()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. 如何使用函数（课本P149）"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 思考函数存在的意义？\n",
    "\n",
    "> 1. 可以通过调用函数的方式实现某个功能，使用人不需要考虑函数代码块的内容\n",
    "> 2. 节省时间，提升应用的效率\n",
    "> 3. 函数一但被定义，就可按照一定规则重复使用"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义一个名叫“search4vowels”函数\n",
    "def search4vowels(word):\n",
    "    \"\"\"\n",
    "    打印文本中出现的元音字母\n",
    "    \"\"\"\n",
    "    vowels = set('aeiou')\n",
    "    found = vowels.intersection(set(word)) # 交集运算\n",
    "    print(found)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on function search4vowels in module __main__:\n",
      "\n",
      "search4vowels(word)\n",
      "    打印文本中出现的元音字母\n",
      "\n"
     ]
    }
   ],
   "source": [
    "help(search4vowels)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'u'}\n"
     ]
    }
   ],
   "source": [
    "search4vowels(\"swhbwdusj\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'u', 'a', 'i', 'e'}\n"
     ]
    }
   ],
   "source": [
    "circle(\"idgefhguagdcy\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "----\n",
    "* 下面的方法重复累赘，主要原因是没有对重复功能的代码块有特殊的定义（如：名称，注释等）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Provide a word to search for vowels:hjdvfiwjhq\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'i'}"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "vowels = set('aeiou')\n",
    "word = input(\"Provide a word to search for vowels:\")\n",
    "found = vowels.intersection(set(word))\n",
    "found"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Provide a word to search for vowels:isgfkjhua\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'a', 'i', 'u'}"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "vowels = set('aeiou')\n",
    "word = input(\"Provide a word to search for vowels:\")\n",
    "found = vowels.intersection(set(word))\n",
    "found"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. 函数的参数\n",
    "\n",
    "* <font style=\"color:red\">注意：函数的参数可以没有，如果有参数，则分为形式参数和实际参数： </font>\n",
    "\n",
    "> 1. 形式参数（形参）\n",
    ">> 1. 在定义过程中，函数的参数为形式参数\n",
    ">> 2. 形参是虚拟的，不占用空间的\n",
    "> 2. 实际参数（实参）\n",
    ">> 1. 调用参数过程中，函数的参数为实参\n",
    ">> 2. 调用函数时，形参被分配空间，成为实参并应用起来"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello world!\n"
     ]
    }
   ],
   "source": [
    "# 函数可以没有参数\n",
    "hey()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义函数\n",
    "def greet_user(username):\n",
    "    \"\"\"\n",
    "    显示简单的问候语，输入你的名字\n",
    "    \"\"\"\n",
    "    print(\"hello,\"+username.title()+\"!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello,Momge!\n"
     ]
    }
   ],
   "source": [
    "# 调用函数：  username = \"momge\"\n",
    "greet_user(\"momge\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 当参数不止一个：\n",
    "> 1. 位置参数（positional argument）\n",
    ">> 1. 形参有多个值，如果实际参数直接赋值，要按照形参的先后顺序，称之为：位置参数赋值\n",
    ">> 2. 在调用函数过程中需考虑：\n",
    ">>> 1. 位置\n",
    ">>> 2. 个数\n",
    "> 2.[关键字参数](https://docs.python.org/3/tutorial/controlflow.html#keyword-arguments)\n",
    ">> 1. 在调用函数时使用，我们直接在实参中 用赋值的方式去定义形参\n",
    ">> 2. 不需要考虑顺序，因为赋值已经确定了形式参数的值\n",
    "> 3. [默认参数](https://docs.python.org/3/tutorial/controlflow.html#default-argument-values)\n",
    ">> 1. 默认参数写在 形式参数中（预计有大量的调用会使用到的值，可以预先设置）\n",
    ">> 2. 默认参数存在的话，实际调用过程中可以省略赋值的过程"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 注意，有两个参数\n",
    "def describe_pet(animal_type,pet_name):\n",
    "    \"\"\"\n",
    "    显示宠物信息\n",
    "    \"\"\"\n",
    "    print(\"\\nI have a \" + animal_type + \".\")\n",
    "    print(\"My \" + animal_type +\"'s name is \" + pet_name.title() + \".\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "I have a cat.\n",
      "My cat's name is 琥珀.\n"
     ]
    }
   ],
   "source": [
    "describe_pet(\"cat\",\"琥珀\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "describe_pet() missing 1 required positional argument: 'pet_name'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-23-5208887e1c6b>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mdescribe_pet\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"cat\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m: describe_pet() missing 1 required positional argument: 'pet_name'"
     ]
    }
   ],
   "source": [
    "describe_pet(\"cat\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "I have a cat.\n",
      "My cat's name is 琥珀.\n"
     ]
    }
   ],
   "source": [
    "# 关键字参数\n",
    "describe_pet(pet_name=\"琥珀\",animal_type=\"cat\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 默认参数（写在形参中）\n",
    "def describe_pet(pet_name,animal_type=\"cat\"):\n",
    "    \"\"\"显示宠物信息，animal_type 的默认值 'cat'\"\"\"\n",
    "    print(\"\\nI have a \" + animal_type + \".\")\n",
    "    print(\"My \" + animal_type + \"'s name is \"+pet_name.title() + \".\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "I have a 琥珀.\n",
      "My 琥珀's name is Cat.\n"
     ]
    }
   ],
   "source": [
    "describe_pet(\"琥珀\",\"cat\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "-------------------\n",
    "\n",
    "* 实操和注意（参数部分）positional argument follows keyword argument\n",
    "\n",
    "> 1. 如果想 关键字参数 和 位置参数共同使用\n",
    ">> 1. positional argument follows keyword argument(位置参数需要放在关键字参数的前面)\n",
    ">> 2. 关键字参数放在末尾（均是关键字，不考虑顺序）\n",
    "> 2. 默认参数\n",
    ">> 1. non-default argument follows default argument(非默认参数需要放在默认参数的前面)\n",
    ">> 2. 默认参数放在末尾（均是默认参数，不考虑顺序）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "positional argument follows keyword argument (<ipython-input-30-26b098ea64bc>, line 6)",
     "output_type": "error",
     "traceback": [
      "\u001b[1;36m  File \u001b[1;32m\"<ipython-input-30-26b098ea64bc>\"\u001b[1;36m, line \u001b[1;32m6\u001b[0m\n\u001b[1;33m    func_test(x=1,2)      #？\u001b[0m\n\u001b[1;37m                 ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m positional argument follows keyword argument\n"
     ]
    }
   ],
   "source": [
    "#eg1 \n",
    "def func_test(x,y):\n",
    "    print(x)\n",
    "    print(y)\n",
    "    \n",
    "func_test(x=1,2)      #？"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n",
      "1\n",
      "3\n"
     ]
    }
   ],
   "source": [
    "#eg2\n",
    "def func_test(x,y,z):\n",
    "    print(x)\n",
    "    print(y)\n",
    "    print(z)\n",
    "    \n",
    "func_test(2,1,z=3)      "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "non-default argument follows default argument (<ipython-input-32-72e60920b1b2>, line 2)",
     "output_type": "error",
     "traceback": [
      "\u001b[1;36m  File \u001b[1;32m\"<ipython-input-32-72e60920b1b2>\"\u001b[1;36m, line \u001b[1;32m2\u001b[0m\n\u001b[1;33m    def func_test(x,y=4,z):\u001b[0m\n\u001b[1;37m                 ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m non-default argument follows default argument\n"
     ]
    }
   ],
   "source": [
    "#eg3\n",
    "def func_test(x,y=4,z):\n",
    "    print(x)\n",
    "    print(y)\n",
    "    print(z)\n",
    "    \n",
    "func_test(2,1,3)    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n",
      "5\n",
      "3\n"
     ]
    }
   ],
   "source": [
    "#eg3\n",
    "def func_test(x,z,y=3):\n",
    "    print(x)\n",
    "    print(y)\n",
    "    print(z)\n",
    "    \n",
    "func_test(2,3,5)    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
